package cn.aigoubuy.web.servelt;

import cn.aigoubuy.domain.PageBean;
import cn.aigoubuy.domain.Product;
import cn.aigoubuy.service.ProductService;
import cn.aigoubuy.service.impl.ProductServiceImpl;
import cn.aigoubuy.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/productServlet")
public class ProductServlet extends BaseServlet {
    // 通过id查询详情
    public String findById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.接收参数
        String pid = request.getParameter("pid");
        // 2.调用service查询
        ProductService productService = new ProductServiceImpl();
        Product product = productService.findById(pid);
        // 3.1 将查询结果放到request域中
        request.setAttribute("product",product);
        // 3.2 页面跳转
        return "/jsp/product_info.jsp";
    }

    /**
     * 通过分类 id 查询所有商品
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String findByCid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1 接收参数
        // 1.1 分类 id
        String cid = request.getParameter("cid");
        // 1.2 当前页
        int pageNumber = 1;
        String pageNumberStr = request.getParameter("num");
        try {
            if(pageNumberStr != null) {
                //没有传递参数，或参数错误，使用默认值 1
                pageNumber = Integer.parseInt(pageNumberStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 1.3 每页显示个数
        int pageSize = 12; //固定值，可以通过请求参数获得
        // 2 调用业务层：
        ProductService productService = new ProductServiceImpl();
        PageBean<Product> pageBean = productService.findByCid(cid,pageNumber,pageSize);
        // 3 将数据存放 request 作用域，并请求转发到指定的 jsp
        request.setAttribute("page", pageBean);
        return "/jsp/product_list.jsp";
    }
}